/**
 *
type：  2-簿记新增    3-详情 
info：type=3 || 4时，需回填字段
onRef：组件指针
getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
reset：通过onRef，调用reset方法，清空页面字段
portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
tradingCodeOnChange：合约代码变更事件，输出当前合约代码id，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import moment from 'moment';
import investmentType from '../../../../utils/enumeratedValues/investmentType';
const FormItem = Form.Item;
const FormItemLayout = {
  labelCol: {
    xl: { span: 8, offset: 0 },
    xxl: { span: 8, offset: 0 },
  },
  wrapperCol: {
    xl: { span: 15, offset: 0 },
    xxl: { span: 15, offset: 0 },
  },
};

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //详情
    type: undefined, //当前指令的类型
    SecuritiesCode: undefined, //证券代码val值
    investmentTypeList: [...investmentType], //投资类型下拉
  };
  componentDidMount() {
    this.props.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.props.futuresInfo) != JSON.stringify(nextProps.futuresInfo)) {
      const {
        form: { setFieldsValue, getFieldValue },
      } = this.formGroupThis.props;
      //重新计算合约价值 合约保证金
      this.changeNum(getFieldValue('price'), 'price');
    }
    if (JSON.stringify(this.props.position) != JSON.stringify(nextProps.position)) {
      const {
        form: { setFieldsValue: setValues, getFieldValue: getValue },
      } = this.formGroupThis.props;
      let position = nextProps.position;
      // 投资类型、合约代码、交易市场回填；
      //当【多空标志】为“多头”时，指令下达中的【交易方向】回填“卖出平仓”；
      //当【多空标志】为“空头”时，指令下达中的【交易方向】回填“买入平仓”。
      this.setState({
        //设置tradingCode
        SecuritiesCode: {
          tradingCode: position.tradingCode,
        },
      });
      setValues({
        zqdm: position.tradingCode ? `${position.exchangeCode}-${position.tradingCode}` : undefined,
        investmentType: position.investmentType,
        exchangeCode: position.exchangeCode,
        direction: position.stockType ? (position.stockType == '1' ? 'W' : 'Y') : undefined,
      });
    }
  }
  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
  };
  //证券代码切换
  securitiesCodeChange = (value) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    const { info } = this.props;
    if (info) return; //详情时不进入判断
    this.setState({
      SecuritiesCode: value,
    });
    setFieldsValue({
      exchangeCode: value ? value.exchangeCode : undefined,
    });
    this.props.tradingcodeOnChange(value);
  };
  //交易方向变更
  changeDirect = (e) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.info) return; //详情时不计算
    setFieldsValue({ direction: e?.value });
    this.calcEarnestMoney(); //计算保证金
  };
  //获取当前表单数据 并校验
  getInfo = () => {
    const {
      user: { currentUser },
      money = {},
      holdData = [],
    } = this.props;
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;

    validateFields((err, fieldsValue) => {
      if (!err) {
        if (fieldsValue.direction == 'V' || fieldsValue.direction == 'X') {
          //V-买入开仓  W-卖出平仓  X-卖出开仓  Y-买入平仓
          //【交易方向】为“买入开仓”或“卖出开仓”时，进行验资，合约保证金需小于可用保证金；
          if (fieldsValue.earnestMoney > (money.remainingSum || 0)) {
            message.warning('合约保证金需小于可用保证金!');
            return;
          }
        } else {
          //【交易方向】为“卖出平仓”或“买入平仓”时，进行验券，卖出平仓的数量需小于等于对应合约多头的持仓数量，买入平仓的数量需小于等于对应合约空头的持仓数量
          for (let index = 0; index < holdData.length; index++) {
            let item = holdData[index];
            if (fieldsValue.direction == 'W') {
              if (`${item.exchangeCode + '-' + item.tradingCode}` == fieldsValue.zqdm) {
                if (fieldsValue.amount > item.holdNum && item.stockType == '1') {
                  message.warning('卖出平仓的数量需小于等于对应合约多头的持仓数量!');
                  return;
                }
              }
            } else {
              if (`${item.exchangeCode + '-' + item.tradingCode}` == fieldsValue.zqdm) {
                if (fieldsValue.amount > item.holdNum && item.stockType == '2') {
                  message.warning('买入平仓的数量需小于等于对应合约空头的持仓数量!');
                  return;
                }
              }
            }
          }
        }
        if (fieldsValue.direction == 'V' || fieldsValue.direction == 'W') {
          //当【交易方向】为“买入开仓”或“卖出平仓”时，即“多头”，参数tradeType:23 下达时传给后端;
          fieldsValue.tradeType = '23';
        } else {
          //当【交易方向】为“卖出开仓”或“买入平仓”时，即“空头”， 参数tradeType:24 下达时传给后端
          fieldsValue.tradeType = '24';
        }
        query = fieldsValue;
        query.tradingCode = this.state.SecuritiesCode?.tradingCode;
        query.secuabbr = this.state.SecuritiesCode?.secuabbr || this.props.futuresInfo.chinaName;
        delete query.zqdm;
      }
    });
    return query;
  };
  //重置页面数据 取消
  reset = () => {
    const { form } = this.formGroupThis.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); //重置组合id和证券代码
    this.setState({
      info: undefined, //详情
      type: undefined, //当前指令的类型
      SecuritiesCode: undefined, //证券代码val值
      price: undefined,
      amount: undefined,
    });
    form.resetFields();
  };
  //form表单渲染
  formRender = () => {
    const { type, info } = this.props;
    const {
      globalM: {
        dataDictionary: { TZTYPE = [] },
      },
    } = this.props;
    let disabled;
    if (type == 1 || type == 2 || type == 11) {
      disabled = false;
    } else {
      disabled = true;
    }
    return (
      <div className={'formOrder'}>
        <FormGroup
          dataSource={[
            {
              disabled: disabled,
              title: ['产品', '组合'],
              type: DATA_ENTRY.PRODUCTGROUPSEP,
              initialValue: info ? [info.productId, info.portfolioId] : undefined,
              authority: 'write',
              multipleGroup: false,
              dataIndex: ['productId', 'portfolioId'],
              rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
              groupOnChange: (e) => {
                this.groupOnChange(e);
                this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
              },
              productOnChange: (e) => {
                //产品切换清空证券代码数据
                this.formGroupThis.props.form.setFieldsValue({ zqdm: undefined, exchangeCode: undefined });
                this.setState({
                  SecuritiesCode: undefined,
                });
              },
              allowClear: false,
              exist: 1,
              span: 16,
              controlLabelSpan: 6,
              tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
            },
            {
              dataIndex: 'kindOfInvestment',
              title: '投资种类',
              type: DATA_ENTRY.SELECT,
              disabled: disabled,
              initialValue: info ? info.kindOfInvestment : '1',
              dataSource: TZTYPE.map((item) => {
                return { value: item.code, title: item.value };
              }),
              span: 8,
              controlLabelSpan: 6,
              rules: [{ required: true, message: '请选择投资种类!' }],
            },
            {
              dataIndex: 'zqdm',
              title: '合约代码',
              type: DATA_ENTRY.SECURITIESCODE,
              initialValue: info ? `${info.exchangeCode}-${info.tradingCode}` : undefined,
              onChange: (e) => this.securitiesCodeChange(e),
              codeType: codeType.stockIndexFutures,
              rules: [{ required: true, message: '请选择合约代码!' }],
              disabled: disabled,
              queryItems: { time: moment(new Date()).format('YYYY-MM-DD'), exchangeCode: '121' },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              title: '交易市场',
              dataIndex: 'exchangeCode',
              type: DATA_ENTRY.TRADINGMARKET,
              dataType: 1,
              initialValue: info ? info.exchangeCode : undefined,
              marketType: ['guzhi'],
              rules: [{ required: true, message: '请选择交易市场!' }],
              disabled: true,
              span: 8,
              controlLabelSpan: 6,
              onRef: (ref) => (this.formGroupThis = ref), //放在外层 首次无法取到 房内层可以
            },
            {
              dataIndex: 'direction', // Form识别的Item ID
              businessType: '23',
              type: DATA_ENTRY.TRADINGDIRECT,
              disabled: disabled,
              initialValue: info?.direction,
              allowClear: false,
              rules: [{ required: true, message: '请选择交易方向!' }],
              onChange: this.changeDirect,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'price',
              title: '价格',
              unit: '元',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.price : null,
              splitStyle: true,
              rules: [{ required: true, message: '请输入价格!' }],
              precision: 2,
              disabled: disabled,
              onBlur: (e) => {
                this.changeNum(e, 'price');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'amount',
              title: '数量',
              unit: '手',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.amount : null,
              splitStyle: true,
              rules: [{ required: true, message: '请输入数量为正整数', pattern: new RegExp(/^[1-9]\d*$/, 'g') }],
              disabled: disabled,
              precision: 0,
              onBlur: (e) => {
                this.changeNum(e, 'amount');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'totalPrice',
              title: '合约价值',
              unit: '元',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.totalPrice : null,
              splitStyle: true,
              precision: 2,
              disabled: true,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'earnestMoney',
              title: '合约保证金',
              unit: '元',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info ? info.earnestMoney : null,
              splitStyle: true,
              precision: 2,
              disabled: true,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'investmentType',
              title: '投资类型',
              type: DATA_ENTRY.SELECT,
              disabled: disabled,
              initialValue: info ? info.investmentType : 'FVTPL',
              dataSource: investmentType,
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'remark',
              type: DATA_ENTRY.INPUT,
              title: '备注',
              disabled: disabled,
              initialValue: info ? info.remark : undefined,
              placeholder: '请输入',
              showTextArea: true,
              autosize: { minRows: 2, maxRows: 2 },
              span: 24,
              controlLabelSpan: 2,
            },
          ]}
          autoLayout={false}
        />
      </div>
    );
  };

  //修改价格 数量
  changeNum = (e, type) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    if (this.props.info) return; //详情时不计算
    let data = getFieldValue(type);
    this.setState(
      {
        [type]: data,
      },
      () => {
        if (this.state.price !== '' && this.state.price != null) {
          if (this.state.amount !== '' && this.state.amount != null) {
            setFieldsValue({
              totalPrice: parseFloat(this.state.price * this.state.amount) * (this.props.futuresInfo.contractMultiplie || 0), //合约价值 =价格 * 数量 * 合约乘数
            });
          } else {
            setFieldsValue({ totalPrice: null });
          }
        } else {
          setFieldsValue({ totalPrice: null });
        }
        this.calcEarnestMoney(); //计算保证金
      },
    );
  };
  //计算保证金
  calcEarnestMoney = () => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    // 保证金 = 合约价值 * 保证金比例（根据不同的交易方向获取不同的保证金 多头、空头）
    let direction = getFieldValue('direction');
    let totalPrice = getFieldValue('totalPrice');
    let earnestMoney = null;
    let futuresInfo = this.props.futuresInfo;
    if (direction != 'W' && direction != 'Y' && direction) {
      // 平仓时，不计算合约保证金
      let temp = direction == 'V' ? futuresInfo.marginMoneyD : futuresInfo.marginMoneyK;
      earnestMoney = (totalPrice || 0) * (temp || 0);
    }
    setFieldsValue({ earnestMoney: earnestMoney });
  };

  render() {
    return <div className={style.info}>{this.formRender()}</div>;
  }
}
export default connect(({ stockIndexM, globalM, userM: user, loading }) => ({
  stockIndexM,
  globalM,
  user,
  loading,
}))(Form.create()(OrderFormC));
